<?php

namespace App\Http\Controllers\LibApi;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

/**
 * 重庆市图书馆api接口
 */
class CqstLibController
{


    //   private static $appId ='btkk_bxdd_cqst'; //测试环境
    //  private static $appSecret ='123456';//测试环境

    private static $appId = 'cql_miniapps'; //正式环境  与测试环境一致
    private static $appSecret = '123456'; //正式环境

    private static $grantType = 'client_credentials'; //测试环境
    private static $scope = 'read';


    private static $adminName = 'cql_miniapps'; //正式地址  操作管理员账号 与测试环境一致`
    private static $password = 'cql_miniapps@123'; //正式地址  操作管理员密码


    //   private static $serviceAddr = 'http://222.178.152.2:18083';//本地测试服务器地址
    private static $serviceAddr = 'http://222.177.237.237:8088'; //本地测试服务器地址
    // private static $serviceAddr = 'http://125.80.96.7:19007'; //正式服务器外网地址
    // private static $serviceAddr = '';//正式服务器内网地址


    private static $getToken = '/indiglibCloudApi/oauth/token'; //鉴权，获取access_token
    private static $login = '/indiglibCloudApi/api/v1/reader/login'; //front-读者登录-根据证号和密码-校验读者证号密码是否匹配并返回读者基本信息-需授权
    private static $idCardlogin = '/indiglibCloudApi/api/v1/reader/loginByIdnoAndPassword'; //front-读者登录-根据身份证和密码-返回读者列表-需授权
    private static $getReaderCurrentBorrowListPageInfo = '/indiglibCloudApi/api/v1/circulate/getReaderCurrentBorrowListPageInfo'; //流通-查询读者当前借阅分页列表-根据读者证号-需授权
    private static $getHistoryBorrow = '/indiglibCloudApi/api/v1/circulate/getReaderHistoryBorrowPageInfo'; //流通-查询读者历史借阅分页列表-根据读者证号-需授权
    private static $getBookSearchParam = '/indiglibCloudApi/api/v1/front/opacSearch/searchParam'; //书目-opac书目检索-获取检索条件参数
    private static $getBookInfo = '/indiglibCloudApi/api/v1/front/opacSearch/search'; //书目-opac书目检索-检索结果分页列表
    private static $getMarcInfoByMeta = '/indiglibCloudApi/api/v1/marc/getMarcInfoByMeta'; //2.9书目-查询marc书目详细信息-根据metatable，metaid-需授权
    private static $getAssetPageInfoForOpac = '/indiglibCloudApi/api/v1/asset/getAssetPageInfoForOpac'; //馆藏-查询馆藏分页列表-前台opac使用-需授权
    private static $getAssetByBarcode = '/indiglibCloudApi/api/v1/asset/getAssetByBarcode'; //馆藏-查询馆藏分页列表-根据barcode馆藏条码号-需授权
    private static $validateBorrow = '/indiglibCloudApi/api/v1/circulate/validateBorrow'; //2.11流通-校验借书接口-需授权
    private static $renew = '/indiglibCloudApi/api/v1/circulate/renew'; //流通-续借-续借单条-需授权
    private static $validateReturn = '/indiglibCloudApi/api/v1/circulate/validateReturnBook'; //流通-校验归还接口-需授权
    private static $borrow = '/indiglibCloudApi/api/v1/circulate/borrow'; //流通-借书接口-需授权
    private static $returnBook = '/indiglibCloudApi/api/v1/circulate/returnBook'; //流通-还书接口-需授权
    private static $readerIdAdd = '/indiglibCloudApi/api/v1/reader/card/create'; //读者证-办证接口-需授权
    private static $getOnlineReaderCardCreateParam = '/indiglibCloudApi/api/v1/param/onlineReaderCardCreateParam/getOnlineReaderCardCreateParam'; //读者证-在线办证-获取在线办证参数集合

    private static $getReaderPageInfoByIdno = '/indiglibCloudApi/api/v1/reader/getReaderPageInfoByIdno'; //读者-查询读者列表(非注销)-根据身份证号码-需授权
    private static $lost = '/indiglibCloudApi/api/v1/reader/card/readerCardLost/lost'; //读者证-挂失-需授权
    private static $lostRecover = '/indiglibCloudApi/api/v1/reader/card/readerCardRecover/lostRecover'; //读者证-挂失恢复-需授权
    private static $updateReaderPassword = '/indiglibCloudApi/api/v1/reader/card/updateReaderPassword'; //读者证-更新读者密码-需授权

    private static $getReaderArrearsListPageInfo = '/indiglibCloudApi/api/v1/reader/finance/readerFinanceArrears/getReaderArrearsListPageInfo'; //读者财经-欠款-查询读者欠款分页列表-根据读者证号-需授权
    private static $payArrears = '/indiglibCloudApi/api/v1/reader/finance/readerFinanceArrears/payArrears'; //读者财经-欠款-支付欠款-需授权


    private static $getReaderInfo = '/indiglibCloudApi/api/v1/reader/getReaderInfoByCardnoWithBorrowInfoAndFinInfo'; //2.17查询读者(基本信息+借阅信息+财经信息)-根据读者证号-需授权

    //private static $addCirMarcAndAcqWorkAndAssetAndBorrowBook = '/indiglibCloudApi/api/v1/sale/addCirMarcAndAcqWorkAndAssetAndBorrowBook'; //2.13你借书我买单-添加右屏流通书目和采访信息和中央馆藏并借书-需授权
    //少儿接口特殊处理，因为他们是写入一卡通，其他馆是非一卡通
    private static $addCirMarcAndAcqWorkAndAssetAndBorrowBook = '/indiglibCloudApi/api/v1/sale/addUniMarcAndUniAssetWithSendCirMarcAndAssetAndBorrowBook'; //2.13你借书我买单-添加右屏流通书目和采访信息和中央馆藏并借书-需授权


    private static $wxAccessToken = '/indiglibCloudApi/api/v1/weChat/getAccessToken'; //2.23微信-获取微信accessToken，统一分析
    private static $wxBind = '/indiglibCloudApi/api/v1/reader/weChat/bind'; //2.6front-微信-读者绑定-需授权（我们平台绑定后，推送绑定在文华系统）
    private static $wxUnBind = '/indiglibCloudApi/api/v1/reader/weChat/unbind'; //2.7front-微信-解除读者绑定-需授权（我们平台解绑后，推送解绑在文华系统）
    private static $getReaderByOpenid = '/indiglibCloudApi/api/v1/reader/getReaderByOpenid'; //2.23读者-查询读者(基本信息)-根据微信openid-需授权

    private static $validateIdnoIsExist = '/indiglibCloudApi/api/v1/cloud/reader/validateIdnoIsExist'; //云cloud-读者-校验读者身份证号是否存在(校验是否存在非注销状态读者)-需授权
    //  private static $validateIdnoIsExist = '/indiglibCloudApi/api/v1/reader/isIdnoExist';//云cloud-读者-校验读者身份证号是否存在(校验是否存在非注销状态读者)-需授权
    private static $countAsset = '/indiglibCloudApi/api/v1/asset/countAsset'; //客户端调用该协议根据metatable，metaid统计馆藏数量  之前的接口“/indiglibCloudApi/api/v1/front/opacSearch/search”里的参数，assetCount，不能排除馆藏查询，所以使用此接口
    private static $extendByReaderSelf = '/indiglibCloudApi/api/v1/reader/card/readerCardExtend/extendByReaderSelf'; //读者证-证延期-网上服务读者自助延期-需授权


    private static $getReaderById = '/indiglibCloudApi/api/v1/reader/getReaderById'; //读者-查询读者(基本信息)-根据读者id-需授权


    /**
     * 大数据接口
     */
    // private static $readerType = '/indiglibApi/api/v1/param/cardTypeParam/getCardTypeMap'; //获取读者证类型
    // private static $readerStatisticsCount = '/indiglibApi/api/v1/reader/statistics/count'; //读者-统计-根据读者类型等统计读者数量
    // private static $countEvent = '/indiglibApi/api/v1/reader/event/statistics/countEvent'; //2.5读者-统计-根据事务类型以及日期统计事务操作次数
    // private static $getServiceEventPageInfo = '/indiglibApi/api/v1/circulate/serviceEvent/getServiceEventPageInfo'; //2.6流通-查询-查询流通事务列表
    // private static $countServiceEvent = '/indiglibApi/api/v1/circulate/statistics/countServiceEvent'; //2.7流通-统计-根据事务类型以及日期统计事务操作次数
    // private static $countReader = '/indiglibApi/api/v1/circulate/statistics/countReader'; //流通-统计-根据事务类型以及日期统计事务-读者人次
    // private static $assetStatisticsCount = '/indiglibApi/api/v1/asset/statistics/count'; //2.8馆藏-统计-根据馆藏类型等统计馆藏数量
    // private static $assetCountEvent  = '/indiglibApi/api/v1/asset/event/statistics/countEvent'; //2.9馆藏-统计-根据事务类型以及日期统计事务操作次数
    // private static $assetParam  = '/indiglibApi/api/v1/front/borrowRankingList/assetParam'; //2.10front-文献借阅排行榜-获取查询条件参数
    // private static $frontAsset  = '/indiglibApi/api/v1/front/borrowRankingList/asset'; //2.11front-文献借阅排行榜-结果列表
    private static $frontReader  = '/indiglibApi/api/v1/front/borrowRankingList/reader'; //2.12front-读者借阅排行榜-结果列表
    // private static $frontReaderAge  = '/indiglibApi/api/v1/front/borrowRankingList/readerAge'; //2.13前台front-读者年龄借阅排行榜-结果列表



    /**
     * 获取  access_token （已对接）
     */
    public function getAccessToken()
    {
        $url = self::$serviceAddr . self::$getToken;
        $access_token_param = array(
            "grant_type"   => self::$grantType,
            'client_id'    => self::$appId,
            'client_secret' => self::$appSecret,
            'scope'        => self::$scope,
        );

        $access_token_param = http_build_query($access_token_param);
        $result = $this->RequestCurl($url . '?' . $access_token_param, $access_token_param); //必须post请求，但是参数需要像get那样拼接
        $results = json_decode($result, true); //json字符串转为数组

        if (empty($results) || isset($results['error'])) exit(json_encode(['code' => 202, 'msg' => 'access_token获取失败']));

        $access_token = $results['access_token'];
        $expires_in = $results['expires_in'];
        //储存access_token
        Cache::put("lib_access_token", $access_token, $expires_in); //缓存3600秒
        return $access_token;
    }

    /**
     * 登录接口   （已对接） 读者证号登录

    测试账号 一卡通A证  01000000021058
                 密码  123456
     *
     * 读者证状态
     * status
     * n    读者证状态为有效
      y    读者证状态为验证
      l    读者证状态为挂失
      d    读者证状态为注销
      其他或空    读者证状态异常
     *
     * 一共5个对象  新书目 必传 marcInfo  ，已有书目，添加馆藏不用传，其余 4 个对象 都是必传
     * @param $account  读者证号
     * @param $password   密码
     */
    public function login($account, $password)
    {

        // 一个身份证号码对应对个读者证号，所以实现不了
        if (isCreditNo($account)) {
            //判断是否是身份证号登录
            return $this->idCardlogin($account, $password);
        }
        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }


        $url = self::$serviceAddr . self::$login;

        $param = [
            'cardno'  =>  $account,
            'password'  =>  md5($password),
        ];
        $param = json_encode($param);
        // dump($url);
        //  dump($param);
        // die;
        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);

        $results = json_decode($result, true); //json字符串转为数组
        //  dump($results);die;
        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token =  $this->getAccessToken();
            //    cache("lib_access_token" , $access_token , 7200);//缓存7200秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }

        Log::channel('libapi')->info('URL：' . $url);
        Log::channel('libapi')->info(json_decode($param, true));
        //写入错误日志
        Log::channel('libapi')->info($results);

        if ($results['code'] === 1) {
            if ($results['objectData']['status'] == 'n') {
                return ['code' => 200, 'msg' => '登录成功', 'content' => $results['objectData']];
            } elseif ($results['objectData']['status'] == 'l') {
                $msg = '登录失败，该读者证挂失中';
            } elseif ($results['objectData']['status'] == 'd') {
                $msg = '登录失败，该读者证已注销';
            } else {
                $msg = '登录失败，该读者证状态异常';
            }
            return ['code' => 202, 'msg' => $msg];
        }
        return ['code' => 202, 'msg' => '登录失败,读者证号或密码不正确'];
    }

    /**
     * 登录接口（已对接）身份证号登录
     * @param $account  读者证号
     * @param $password   密码
     */
    public function idCardlogin($id_card, $password)
    {
        $account_info = $this->getReaderListByIdCard($id_card, $password);
        if ($account_info['code'] == 200) {
            //登录成功，获取读者信息
            $user_info = $this->getReaderInfo($account_info['content'][0]['cardno']);
            //  dump($user_info);die;
            if ($user_info['code'] == 200) {
                return ['code' => 200, 'msg' => '登录成功', 'content' => $user_info['content']['reader']];
            } else {
                return ['code' => 202, 'msg' => '获取用户信息失败'];
            }
        }
        return ['code' => 202, 'msg' => '登录失败,读者证号或密码不正确'];
    }


    /**
     * 你借书我买单-添加右屏流通书目和采访信息和中央馆藏并借书-需授权
     *
     *  格式             CNMARC
       文献类型          图书
       书目库           CN中央书目库
       馆藏类型          图书
       馆藏所属馆        重庆市渝北区图书馆
       馆藏所属地        重庆市渝北区图书馆
       当前所在馆        新华书店阅读点  YB_XHSD
       当前所在地        新华书店阅读点  YB_XHSD
       经费来源          馆经费
       流通类型          一卡通中文图书
       装帧标识          平装/精装/线装
       载体标识          印刷型文献
     */
    public function addCirMarcAndAcqWorkAndAssetAndBorrowBook($data, $barcode, $account)
    {

        //YZT_CQSC  渝中解放碑重庆书城
        $initSublib = 'BN'; //所属馆
        $initLocal = 'BN_C'; //所属地
        $curSublib = 'BN';  //所在馆
        $curLocal = 'BN_C'; //所在地
        $provider = 'cqsc'; //书商
        $batchNo = date('Y') . '7001'; //批次号 20217001   年份动态变化

        $sublib = 'BN'; //所属馆


        // $initSublib = 'CQST'; //所属馆
        // $initLocal = 'CQST_STYN';//所属地
        // $curSublib = 'CQST';  //所在馆
        // $curLocal = 'CQST_STYN';//所在地
        // //$provider = 'LJXHSD'; //书商//书商：重庆新华传媒有限公司 XHCM、重庆购书中心有限公司
        // $provider = 'XHCM'; //书商//书商：重庆新华传媒有限公司 XHCM、重庆购书中心有限公司 GSZX
        // $batchNo = date('Y').'7001'; //批次号 20217001   年份动态变化

        // $sublib = 'CQST';//所属馆

        //独立书店，馆藏点
        if ($data['shop_id'] == 1) {
            //XHCM  重庆新华传媒有限公司
            $provider = 'XHCM'; //书商
        } elseif ($data['shop_id'] == 2) {
            //GSZX 重庆购书中心有限公司
            $provider = 'GSZX'; //书商
        }

        $adminName = self::$adminName;
        $password = self::$password;


        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token = $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$addCirMarcAndAcqWorkAndAssetAndBorrowBook;
        //判断是写入馆藏还是书目和馆藏同时写入
        $lib_book_info = $this->getBookInfo($data['ISBN']);
        $price = intval($data['price'] * 100); //采访记录的金额
        $param = [];
        $metatable = 'i_biblios'; //书目库
        $metaid = null; //书目记录号

        if ($lib_book_info['code'] == 200) {
            //写入馆藏
            $metatable = $lib_book_info['content']['data'][0]['metatable'];
            $metaid = $lib_book_info['content']['data'][0]['metaid'];
        } else {
            //写入书目信息
            $param['marcInfo'] = [
                'format' => "CNMARC", //1
                "dataType" => "b", //1
                'metatable' => 'i_biblios', //1
                'title' => $data['book_name'],
                'callno' => $data['book_num'],
                'classno' => !empty($data['classno']) ? $data['classno'] : $data['book_num'],
                'ctrlno' => !empty($data['ctrlno']) ? $data['ctrlno'] : '无',
                'page' => (int)!empty($data['page']) ? (int)$data['page'] : 0,
                'isbn' => $data['ISBN'],
                'author' => !empty($data['author']) ? $data['author'] : '无',
                'price' => $data['price'], //单位元
                'publish' => !empty($data['press']) ? $data['press'] : '无',
                'publishTime' => !empty($data['pre_time']) ? $data['pre_time'] : '无',
                'publishName' => !empty($data['press']) ? $data['press'] : '无',
                'publishAddress' => !empty($data['press']) ? $data['press'] : '无',
                'abstractNote' => '无',
                'subject' => '无',
                'topic' => '无',
                'diagonal' => !empty($data['page']) ? (int)$data['page'] : 0,
                'version' => '15',
            ];
        }
        //订阅信息（书目为空的时候要传这个。相当于先做一次订购再添加馆藏。）
        $param['acqWork'] = [
            //  'metaid' => $metaid,   //1
            'metatable' => "i_biblios", //2
            "assetType" => "001",
            'acqType' => 'D', //3
            'acqYear' => date('Y'),
            'acqDate' => date('Y-m-d'),
            //正式环境
            'sublib' => $sublib,
            //测试环境
            // 'sublib' => 'BN',

            'copys' => 1,
            'batchNo' => $batchNo, //批次号
            'orderNo' => $barcode, //订单号，默认和条形码一致
            // 'provider' => 'RT', 测试
            'provider' => $provider, //正式 //书商（来源）

            'finSource' => '01',
            'binding' => 'PZ',
            'carrier' => '01',
            'docSource' => '02',
            'acqFinNo' => '',
            'acqFinDate' => date('Y-m-d'),
            'currency' => 'CNY',
            'price' => $price, //单位分
            'acqCurrency' => 'CNY',
            'acqPrice' => $price, //单位分
            'unitPrice' => $price, //单位分
            'seriesPrice' => $price, //单位分
        ];
        //馆藏信息
        $param['asset'] = [
            // 'metaid' => $metaid,   //1
            'metatable' => $metatable, //1
            "assetType" => "001",
            'barcode' => $barcode, //1
            'classno' => !empty($data['classno']) ? $data['classno'] : $data['book_num'],
            'callno' => $data['book_num'],
            'currency' => 'CNY',
            'unitPrice' => $price,
            'seriesPrice' => $price,
            //正式环境
            'initSublib' => $initSublib, //所属馆
            'initLocal' => $initLocal, //所属地
            'curSublib' => $curSublib,  //所在馆
            'curLocal' => $curLocal, //所在地
            //测试环境
            // 'initSublib' => "BN",
            // 'initLocal' => $initLocal,
            // 'curSublib' => 'BN',
            // 'curLocal' => $curLocal,

            'finSource' => '01',
            'docSource' => '02',
            'cirType' => '001',
            'binding' => 'PZ',
            'carrier' => '01',
            'regDate' => date('Y-m-d'),
            'notes' => '',
            'createDateTime' => date('Y-m-d H:i:s'),
            'updateDateTime' => date('Y-m-d H:i:s'),
        ];
        //借阅信息
        $param['borrowBookInfo'] = [
            'cardno' => $account,
            'borrowDate' => date('Y-m-d'),
            'borrowTime' => date('H:i:d'),
        ];
        //管理员信息
        $param['admin'] = [
            'adminName' => $adminName,
            'password' => md5($password),
            // 'password' => 'ee4dd839109f5112def48acbbaf00113',
            'loginWay' => 'DLibsApi',
            'ip' => '127.0.0.1',
        ];

        $new_book_write_param = $param;
        $param = json_encode($param);

        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组
        // dump($access_token);
        //   dump($results);die;
        //接口报错返回null
        if (empty($results)) {
            return ['code' => 203, 'msg' => '服务器异常，请联系管理员处理'];
        }
        //  dump($result);die;
        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token = $this->getAccessToken();
            // cache("lib_access_token", $access_token, 3600);//缓存3600秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }

        //写入错误日志
        Log::write($new_book_write_param, 'new_book_write_log');
        //写入错误日志
        Log::write($results, 'new_book_write_log');

        if (isset($results['code']) && $results['code'] == 1) {
            return ['code' => 200, 'msg' => '借阅成功', 'content' => $results['objectData']['asset']];
        }

        return ['code' => 202, 'msg' => $results['message']];
    }

    /**
     * 读者登录-根据身份证和密码-返回读者列表-需授权  (已对接)
     * @param $id_card  读者证号
     * @param $password   密码
     */
    public function getReaderListByIdCard($id_card, $password)
    {
        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$idCardlogin;
        $param = [
            'idno'  =>  $id_card,
            'password'  =>  md5($password),
        ];
        $param = json_encode($param);
        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token =  $this->getAccessToken();
            // cache("lib_access_token" , $access_token , 7200);//缓存7200秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }

        Log::channel('libapi')->info('URL：' . $url);
        Log::channel('libapi')->info(json_decode($param, true));
        //写入错误日志
        Log::channel('libapi')->info($results);

        if (empty($results)) {
            return ['code' => 203, 'msg' => '服务器异常，请联系管理员处理'];
        }

        if (isset($results['code']) && $results['code'] == 1 && !empty($results['objectData'])) {
            return ['code' => 200, 'msg' => '获取成功', 'content' => $results['objectData']];
        }
        return ['code' => 202, 'msg' => '获取失败'];
    }

    /**
     * 查询读者(基本信息+借阅信息+财经信息)-根据读者证号-需授权   （已对接）
     * @param $cardno  读者证号
     *
     *  "readerBorrowInfo": {                   //  字段 ： eCardType ， 云服务不为空的就是云服务一卡通，云服务为空的就是本地非一卡通。
           "ableBorrowNum": 10,                //“本地非一卡通” 书还能借多少本      数量独立计算
           "cloudAbleBorrowNum": 9,            //“云服务一卡通” 书还能借多少       数量独立计算
           "ableBorrowNumNote": "本(10)云(9)",   //可借数和已借数，分为“本地非一卡通”书还能借多少，“云服务一卡通”书还能借多少
           "currentBorrowNum": 0,               //“本地非一卡通” 书已借多少本      数量独立计算
           "cloudCurrentBorrowNum": 1,          //“云服务一卡通” 书已借多少       数量独立计算
           "currentBorrowNumNote": "本(0)云(1)",
           "reservationNum": 0
       },
     */
    public function getReaderInfo($account)
    {
        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$getReaderInfo;
        $param = [
            'cardno'  =>  $account,
        ];

        $param = json_encode($param);
        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组
        //  dump($results);die;
        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token =  $this->getAccessToken();
            // cache("lib_access_token" , $access_token , 7200);//缓存7200秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }

        Log::channel('libapi')->info('URL：' . $url);
        Log::channel('libapi')->info(json_decode($param, true));
        //写入错误日志
        Log::channel('libapi')->info($results);

        if ($results['code'] === 1) {
            return ['code' => 200, 'msg' => '获取成功', 'content' => $results['objectData']];
        }
        return ['code' => 202, 'msg' => '读者财经信息获取失败'];
    }


    /**
     * 书目-opac书目检索-获取检索条件参数  (已对接)
     */
    public function getBookSearchParam()
    {
        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }
        // dump($access_token);die;

        $url = self::$serviceAddr . self::$getBookSearchParam;
        $param = '{}';

        //  $param = json_encode($param);

        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token =  $this->getAccessToken();
            //cache("lib_access_token" , $access_token , 7200);//缓存7200秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }

        if ($results['code'] === 1) {
            return ['code' => 200, 'msg' => '获取成功', 'content' => $results['objectData']];
        }
        return ['code' => 202, 'msg' => '获取失败'];
    }

    /**
     * 馆藏-查询馆藏分页列表-根据barcode馆藏条码号-需授权
     * @param $barcode 条形码
     *
     * //ecardflag 为1 则为一卡通。其它情况为非一卡通。
     */
    public function getAssetByBarcode($barcode)
    {
        $barcode = str_replace(config('other.lib_book_prefix'), '', $barcode);

        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$getAssetByBarcode;
        $param = [
            'barcode'  =>  $barcode,
        ];

        $param = json_encode($param);

        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token =  $this->getAccessToken();
            //  cache("lib_access_token" , $access_token , 7200);//缓存7200秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }
        // dump($url);
        // dump($param);
        //   dump($results);die;

        if (!isset($results['code']) || $results['code'] !== 1) {
            return ['code' => 201, 'msg' => '获取失败'];
        }

        if ($results['code'] === 1 && !empty($results['objectData'])) {
            //重新赋值索书号，解决有时没返回的bug
            $results['objectData']['marcInfo']['callno'] = $results['objectData']['asset']['callno'];

            return ['code' => 200, 'msg' => '获取成功', 'content' => $results['objectData']];
        }
        return ['code' => 202, 'msg' => '暂无数据'];
    }


    /**
     * 当前借阅记录   （已对接）
     * @param account 读者证号
     * @param page 页数
     * @param limit 读者证号
     * @param $ban_code 条形码
     * @return array
     */
    public function getNowBorrowList($account, $pageNum = 1, $pageSize = 10, $ban_code = null)
    {
        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }
        $url  = self::$serviceAddr . self::$getReaderCurrentBorrowListPageInfo;
        $param = [
            'pageNum'       =>  $pageNum,
            'pageSize'      =>  $pageSize,
            'cardno'        =>  $account,
        ];

        $param = json_encode($param);
        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token =  $this->getAccessToken();
            // cache("lib_access_token" , $access_token , 3600);//缓存3600秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }
        //  dump($results);die;
        if (!isset($results['objectData']['total']) || $results['objectData']['total'] === 0 || empty($results['objectData']['list'])) {
            return ['code' => 202, 'msg' => '暂无数据'];
        }
        $data = [];
        $i = 0;
        //  dump($param);
        foreach ($results['objectData']['list'] as $key => $val) {
            if (!empty($ban_code)) {
                if ($val['asset']['barcode'] == $ban_code) {
                    $data[0]['lib_name'] = config('other.lib_name');
                    $data[0]['book_name'] = $val['marcInfo']['title'];
                    $data[0]['author'] = $val['marcInfo']['author'];
                    $data[0]['book_num'] = $val['marcInfo']['callno'];
                    $data[0]['price'] = isset($val['asset']['unitPriceYuan']) ? $val['asset']['unitPriceYuan'] : (isset($val['asset']['unitPriceString']) ? $val['asset']['unitPriceString'] : sprintf('%.2f', $val['asset']['unitPrice'] / 100));
                    $data[0]['barcode'] = $val['asset']['barcode'];

                    // $data[0]['borrow_time'] = explode("，", explode("借出日期：", $val['notes'])[1])[0];
                    $data[0]['borrow_time'] = $val['asset']['loanDate'];
                    $data[0]['expire_time'] = $val['asset']['returnDate'];
                    $data[0]['ISBN'] = $val['marcInfo']['isbn'];
                    $data[0]['press'] = $val['marcInfo']['publish'];
                    // $data[0]['callno'] = $val['callno'];//书目索取号
                    break;
                }
            } else {
                $data[$i]['lib_name'] = config('other.lib_name');
                $data[$i]['book_name'] = $val['marcInfo']['title'];
                $data[$i]['author'] = $val['marcInfo']['author'];
                $data[$i]['book_num'] = $val['marcInfo']['callno'];
                // $data[$i]['price'] = isset($val['asset']['unitPriceYuan']) ? $val['asset']['unitPriceYuan'] : $val['asset']['unitPriceString'];
                $data[$i]['price'] = isset($val['asset']['unitPriceYuan']) ? $val['asset']['unitPriceYuan'] : (isset($val['asset']['unitPriceString']) ? $val['asset']['unitPriceString'] : sprintf('%.2f', $val['asset']['unitPrice'] / 100));

                $data[$i]['barcode'] = $val['asset']['barcode'];

                // $data[0]['borrow_time'] = explode("，", explode("借出日期：", $val['notes'])[1])[0];
                $data[$i]['borrow_time'] = $val['asset']['loanDate'];
                $data[$i]['expire_time'] = $val['asset']['returnDate'];
                $data[$i]['ISBN'] = $val['marcInfo']['isbn'];
                $data[$i]['press'] = $val['marcInfo']['publish'];
                $i++;
            }
        }
        if ($data) {
            return ['code' => 200, 'msg' => '获取成功', 'content' => $data];
        }
        return ['code' => 202, 'msg' => '暂无数据'];
    }

    /**
     * 查询读者历史借阅分页列表-根据读者证号 （已对接）
     * @param account 读者证号
     * @param pageNum 分页页码
     * @param pageSize 分页大小
     * @param year 借阅年份，不传默认为今年
     * @param startDate 借阅开始日期
     * @param endDate 借阅结束日期
     *
     * @param $all 是否返回所有数据   true  是  false  不是
     *
     * @return array
     */
    /** 读者借出Ea  */
    //BORROW("Ea", "读者借出"),
    /** 读者还回文献Eg */
    //  RETURN("Eg", "读者还回文献"),    //下面的枚举值，不能管什么情况，都会产生一条这个数据
    /** 读者续借Eb */
    // RENEW("Eb", "读者续借"),
    /** 读者过期Ec */
    //  OVERDUE("Ec", "读者过期"),
    /** 文献损坏Ed */
    //  DAMAGE("Ed", "文献损坏"),
    /** 读者丢失文献Ef */
    //  LOST("Ef", "读者丢失文献"),

    //文华状态
    /**
     * @return  RETURN("Eg", "读者还回文献"),
     * OVERDUE("Ec", "读者过期"),
     * DAMAGE("Ed", "文献损坏"),
     * 书已经还回
     *
     * LOST("Ef", "读者丢失文献"),
     *  书丢失，未还回。
     * 在我们系统    书丢失  也是指归还成功
     */
    public function getReturnData($account, $pageNum = 1, $pageSize = 100, $year =  null, $startDate = null, $endDate = null, $barcode = null, $all = false)
    {

        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }
        $startDate = !empty($startDate) ? $startDate : date("Y-01-01");
        $endDate = !empty($endDate) ? $endDate : date("Y-m-d");
        $url  = self::$serviceAddr . self::$getHistoryBorrow;
        $param = [
            'sortName'      =>  "id", //排序字段
            'sortOrder'     =>  'desc',
            'pageNum'       =>  $pageNum,
            'pageSize'      =>  $pageSize,
            'cardno'        =>  $account,
            'startDate'     =>  $startDate,
            'endDate'       =>  $endDate, //必须要和year 保持在同一年才行
            'year'          =>  $year, //以年为准，如果不传年默认为当年
        ];

        $param = json_encode($param);
        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token =  $this->getAccessToken();
            //  cache("lib_access_token" , $access_token , 3600);//缓存3600秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }

        if (empty($results['objectData']['total']) || $results['objectData']['total'] === 0 || empty($results['objectData']['list'])) {
            return ['code' => 202, 'msg' => '暂无数据'];
        }

        //如果是all，返回所有数据
        if ($all) {
            return $results['objectData'];
        }

        $data = [];
        $i = 0;

        foreach ($results['objectData']['list'] as $key => $val) {
            if (!empty($barcode)) {
                //只返回所有包含当前条形码的记录
                if ($val['barcode'] == $barcode) {
                    $data[$i]['lib_name'] = config('other.lib_name');
                    $data[$i]['event_type'] = $val['eventType']; //返回状态
                    $data[$i]['book_name'] = $val['title'];
                    $data[$i]['author'] = $val['author'];
                    $data[$i]['book_num'] = $val['callno'];
                    $data[$i]['price'] = $val['price'];
                    $data[$i]['barcode'] = $val['barcode'];

                    $borrow_time = explode("借出日期：", $val['notes']);
                    $borrow_time = isset($borrow_time[1]) ? explode("，", $borrow_time[1])[0] : '暂无借阅时间';
                    $data[$i]['borrow_time'] = $borrow_time;
                    // $data[$i]['return_time'] = explode("实际还回日期：" , $val['notes'])[1];
                    $data[$i]['return_time'] = $val['updateDateTime'];
                    $data[$i]['ISBN'] = $val['isbn'];
                    $data[$i]['press'] = $val['publish'];
                    $data[$i]['callno'] = $val['callno']; //书目索取号
                    $i++;
                }
            } else {
                //只返回已归还的记录
                if ($val['eventType'] === 'Eg' || $val['eventType'] === 'Ec' || $val['eventType'] === 'Ed' || $val['eventType'] === 'Ef') {
                    $data[$i]['lib_name'] = config('other.lib_name');
                    $data[$i]['book_name'] = $val['title'];
                    $data[$i]['author'] = $val['author'];
                    $data[$i]['book_num'] = $val['callno'];
                    $data[$i]['price'] = $val['price'];
                    $data[$i]['barcode'] = $val['barcode'];
                    $borrow_time = explode("借出日期：", $val['notes']);
                    $borrow_time = isset($borrow_time[1]) ? explode("，", $borrow_time[1])[0] : '暂无借阅时间';
                    $data[$i]['borrow_time'] = $borrow_time;
                    if (strlen($data[$i]['borrow_time']) == 10) {
                        $data[$i]['borrow_time'] = $data[$i]['borrow_time'] . ' 00:00:00';
                    }
                    // $data[$i]['return_time'] = explode("实际还回日期：" , $val['notes'])[1];
                    $data[$i]['return_time'] = $val['updateDateTime'];
                    $data[$i]['ISBN'] = $val['isbn'];
                    $data[$i]['press'] = $val['publish'];
                    $data[$i]['callno'] = $val['callno']; //书目索取号
                    $i++;
                }
            }
        }

        if ($data) {
            return ['code' => 200, 'msg' => '获取成功', 'content' => $data];
        }
        return ['code' => 202, 'msg' => '暂无数据'];
    }

    /**
     * 书目-opac书目检索-检索结果分页列表   (已对接)
     * @param $content 检索条件  一维数组
     * @param $sortName 排序字段   id   score
     * @param $sortOrder 排序方式
     * @param $page 页数
     * @param $limit 限制条数
     * @param $selectList 请求数据  ['isbn']
     *                              all 任意词
     *                              title 书名
                                   author 作者
                                   classno 分类号
                                   isbn isbn号
                                   callno 索书号
     *                              pubdate  出版年
     *                              publisher  出版社
     *                              subject  主题
     *                              ctrlno   控制号
     * @param $occurList 方式   ['and']    用大写的  AND 或 OR
     * @param $localList //查询(所属)馆藏地点 （馆藏书只能借阅这部分的书籍）
     *                默认图书馆馆藏地点代码： 查询馆藏地点  （书目，所属馆藏地点）
     *                查询的书目，只要有一本在这个馆藏，都可以查询出来
     *
     * @param $curLocalList //查询(所在)馆藏地点
     *
     */
    public function getBookInfo($content, $sortName = "id", $sortOrder = "desc", $page = 1, $limit = 10, $selectList = ["isbn"], $occurList =  ["AND"], $localList = null, $curLocalList = null)
    {
        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }

        $url  = self::$serviceAddr . self::$getBookInfo;

        $param = [
            'sortName'       =>  $sortName,
            'sortOrder'      =>  $sortOrder,
            'pageNum'        =>  $page,
            'pageSize'       =>  $limit,
            'selectList'     =>  $selectList,
            'occurList'      =>  $occurList,
            'textList'       =>  is_array($content) ? $content : [$content],
        ];

        //$localList = 'BN_C';
        if (!empty($localList)) {
            $param['localList'] = is_array($localList) ? $localList : [$localList]; //查询（所属）馆藏地点
        }

        if (!empty($curLocalList)) {
            $param['curLocalList'] = is_array($curLocalList) ? $curLocalList : [$curLocalList]; //查询（所在）馆藏地点
        }
        // if (!empty($curLocalList)) {
        //     $param['initLocalList'] = is_array($curLocalList) ? $curLocalList : [$curLocalList]; //查询（原）馆藏地点
        // }
        //  dump($url);
        //  dump($param);
        $param = json_encode($param);
        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组
        //  dump($results);die;
        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token =  $this->getAccessToken();
            // cache("lib_access_token" , $access_token , 7200);//缓存7200秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }

        if ($results['code'] === 1 && !empty($results['objectData']['list'])) {
            $data = [];
            foreach ($results['objectData']['list'] as $key => $val) {
                $data['data'][$key]['metaid'] = $val['metaid'];
                $data['data'][$key]['metatable'] = $val['metatable'];
                $data['data'][$key]['book_name'] = $val['title'];
                $data['data'][$key]['author'] = isset($val['author']) ? $val['author'] : null;
                $data['data'][$key]['callno'] = isset($val['callno']) ? $val['callno'] : null; //索书号
                $data['data'][$key]['price'] = isset($val['price']) ? $val['price'] : null;

                $data['data'][$key]['ISBN'] = isset($val['isbn']) ? $val['isbn'] : null;

                $data['data'][$key]['img'] = '/default/default_book.png';

                $data['data'][$key]['press'] = trim(explode(',', $val['publish'])[0]);
                $data['data'][$key]['pre_time'] = $val['publishTime'];
                $data['data'][$key]['holding_num'] = $val['assetCount']; //馆藏数量
                $data['data'][$key]['sublibAssetList'] = $val['sublibAssetList']; //分馆馆藏列表
            }
            $data['total'] = $results['objectData']['total'];
            $data['current_page'] = $results['objectData']['pageNum'];
            $data['per_page'] = $results['objectData']['pageSize'];
            $data['last_page'] = $results['objectData']['pages'];
            return ['code' => 200, 'msg' => '获取成功', 'content' => $data];
        }
        return ['code' => 202, 'msg' => '暂无数据'];
    }

    /**
     * //客户端调用该协议根据metatable，metaid统计馆藏数量  之前的接口“/indiglibApi/api/v1/front/opacSearch/search”里的参数，assetCount，不能排除馆藏查询，所以使用此接口
     *access_token	是	String	令牌码
     *   metatable	是	String	书目库
     *   metaid	是	String	书目记录号
        initSublibList			包含所属馆	"initSublibList": ["CQL_DFWX","002"],
        notInInitSublibList			不在该所属馆	"notInInitSublibList": ["CQL_DFWX","002"],
        curSublibList			包含当前馆	"curSublibList": ["CQL_DFWX","002"],
        notInCurSublibList			不在该当前馆	"notInCurSublibList": ["CQL_DFWX","002"],
        initLocalList			包含所属馆藏地点	"initLocalList": ["CQL_DFWX","002"],
        notInInitLocalList			不在该所属馆藏地点	"notInInitLocalList": ["CQL_DFWX","002"],
        curLocalList			包含当前馆藏地点	"curLocalList": ["CQL_DFWX","002"],
        notInCurLocalList			不在该当前馆藏地点	"notInCurLocalList": ["CQL_DFWX","002"],
        inCirTypeList			包含流通类型	"inCirTypeList": ["CQL_DFWX","002"],
        notInCirTypeList			不在该流通类型	"notInInitLocalList": ["CQL_DFWX","002"],
     */
    public function countAssetNum($metatable, $metaid, $initSublibList = [], $notInInitSublibList = [], $curSublibList = [], $notInCurSublibList = [], $initLocalList = [], $notInInitLocalList = [], $curLocalList = [], $notInCurLocalList = [], $inCirTypeList = [], $notInCirTypeList = [])
    {

        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }

        $url  = self::$serviceAddr . self::$countAsset;

        $param = [
            'metatable'      => $metatable,
            'metaid'         => (int)$metaid,
            'initSublibList'       => $initSublibList,
            'notInInitSublibList'  => $notInInitSublibList,
            'curSublibList'        => $curSublibList,
            'notInCurSublibList'   => $notInCurSublibList,
            'initLocalList'        => $initLocalList,
            'notInInitLocalList'   => $notInInitLocalList,
            // 'notInInitLocalList'   => ["CQL_DFWX","002"],
            'curLocalList'         => $curLocalList,
            'notInCurLocalList'    => $notInCurLocalList,
            'inCirTypeList'        => $inCirTypeList,
            'notInCirTypeList'     => $notInCirTypeList,
        ];

        $param = json_encode($param);
        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组
        // dump($results);
        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token =  $this->getAccessToken();
            //  cache("lib_access_token" , $access_token , 7200);//缓存7200秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }


        Log::channel('libapi')->info('URL：' . $url);
        Log::channel('libapi')->info(json_decode($param, true));
        //写入错误日志
        Log::channel('libapi')->info($results);

        //接口报错返回null
        if (empty($results)) {
            return ['code' => 203, 'msg' => '服务器异常，请联系管理员处理'];
        }
        if ($results['code'] === 1 && !empty($results['objectData'])) {
            return ['code' => 200, 'msg' => '获取成功', 'content' => $results['objectData']];
        }
        return ['code' => 202, 'msg' => '获取馆藏数量失败'];
    }
    /**
     * 书目-查询marc书目详细信息-根据metatable，metaid-需授权
     * @param  $metatable 书目库
     * @param  $metaid 书目记录号
     */
    public function getBookDetail($metatable, $metaid)
    {
        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }

        $url  = self::$serviceAddr . self::$getMarcInfoByMeta;
        $param = [
            'metatable'       =>  $metatable,
            'metaid'          =>  (int)$metaid,
        ];

        $param = json_encode($param);
        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token =  $this->getAccessToken();
            // cache("lib_access_token" , $access_token , 7200);//缓存7200秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }
        //  dump($url . '?access_token=' . $access_token);
        //  dump($results);die;
        if ($results['code'] === 1 && !empty($results['objectData'])) {
            $data['metaid'] = $results['objectData']['metaid'];
            $data['metatable'] = $results['objectData']['metatable'];
            $data['book_name'] = $results['objectData']['title'];
            $data['author'] = $results['objectData']['author'];
            $data['book_num'] = $results['objectData']['callno'];  //返回了 classno （分类号） 和 callno（索书号）
            $data['classno'] = $results['objectData']['classno'];  //返回了 classno （分类号） 和 callno（索书号）
            $data['price'] = $results['objectData']['price'];
            $data['page'] = $results['objectData']['page'];
            $data['intro'] = $results['objectData']['note'];

            $data['ISBN'] = $results['objectData']['isbn'];
            $data['press'] = $results['objectData']['publishName'];
            $data['pre_time'] = $results['objectData']['publishTime'];
            // $data[$key]['holding_num'] = $val['assetCount'];//馆藏数量
            // $data[$key]['sublibAssetList'] = $val['sublibAssetList'];//分馆馆藏列表

            return ['code' => 200, 'msg' => '获取成功', 'content' => $data];
        }
        return ['code' => 202, 'msg' => '暂无数据'];
    }


    /**
     * 馆藏-查询馆藏分页列表-前台opac使用-需授权
     * @param  $metatable 书目库
     * @param  $metaid 书目记录号
     *
     * 返回  的status  状态     */
    /** 分编a ，不在opac上显示 */
    //CAT("a", "分编"),
    /** 入藏b*/
    //ONSHELF("b", "入藏"),
    /** 在装订c */
    //BINDING("c", "在装订"),
    /** 已合并d */
    //MERGED("d", "已合并"),
    /** 修补e */
    //REPAIRING("e", "修补"),
    /** 丢失f ，不在opac上显示 */
    //LOST("e", "丢失"),
    /** 剔除g ，不在opac上显示 */
    //DISCARD("g", "剔除"),
    /** 普通借出h */
    //LOAN("h", "普通借出"),
    /** 预约i */
    //RENT_LOAN("i", "预约"),
    /** 阅览借出j */
    //READING_LOAN("j", "阅览借出"),
    /** 资产状态:租出 k */
    //LEASE("k", "资产状态"),
    /** 预借l */
    //RESERVE("l", "预借"),
    /** 互借m */
    //INTER_LOAN("m", "互借"),
    /** 闭架借阅n */
    //CLOSE_LOAN("n", "闭架借阅"),
    /** 赠送o ，不在opac上显示 */
    //GIFT("o", "赠送"),
    /** 交换出p ，不在opac上显示 */
    //EXCHANGE("p", "交换出"),
    /** 调拨q ，不在opac上显示 */
    //DISPATCH("q", "调拨"),
    /** 转送t ，不在opac上显示 */
    //TRANSMIT("t", "转送"),
    /** 临时借出x ，不在opac上显示 */
    //TEMP_LOAN("x", " 临时借出"),
    /** 下架  */
    //SHELVES("s", "下架"),

    //ecardflag 为1 则为一卡通。其它情况为非一卡通。

    //$curLocalList 馆藏点  只允许查询的馆藏点

    public function getAssetPageInfoForOpac($metatable, $metaid, $curLocalList = null, $page = 1, $limit = 100)
    {
        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }

        $url  = self::$serviceAddr . self::$getAssetPageInfoForOpac;
        $param = [
            'sortName'          =>  'id',
            'sortOrder'          =>  'desc',
            'metatable'       =>  $metatable,
            'metaid'          =>  (int)$metaid,
            'pageNum'          =>  (int)$page,
            'pageSize'          =>  (int)$limit,
        ];
        $param = json_encode($param);
        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token =  $this->getAccessToken();
            // cache("lib_access_token" , $access_token , 7200);//缓存7200秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }
        // dump($results);
        if ($results['code'] === 1 && !empty($results['objectData']["list"])) {
            $data = [];
            $i = 0;
            foreach ($results['objectData']['list'] as $key => $val) {
                if (!empty($curLocalList) && !in_array($val['curLocal'], $curLocalList)) {
                    continue;
                }

                $data[$i]['metaid'] = $val['metaid'];
                $data[$i]['metatable'] = $val['metatable'];
                $data[$i]['status'] = $val['status'];
                $data[$i]['status_name'] = $this->getBookStatusName($val['status']);
                $data[$i]['barcode'] = $val['barcode'];
                $data[$i]['book_num'] = $val['callno'];
                $data[$i]['initSublib'] = $val['initSublib']; //馆藏所属馆
                $data[$i]['initLocal'] = $val['initLocal']; //馆藏所属地
                $data[$i]['curSublib'] = isset($val['curSublib']) ? $val['curSublib'] : $val['initSublib']; //当前所在馆
                $data[$i]['curLocal'] = isset($val['curLocal']) ? $val['curLocal'] : $val['initLocal']; //当前所在地
                $data[$i]['initSublibNote'] = $val['initSublibNote']; //馆藏所属馆
                $data[$i]['initLocalNote'] = $val['initLocalNote']; //馆藏所属地
                $data[$i]['curSublibNote'] = isset($val['curSublibNote']) ? $val['curSublibNote'] : $val['initSublibNote']; //当前所在馆
                $data[$i]['curLocalNote'] = isset($val['curLocalNote']) ? $val['curLocalNote'] : $val['initLocalNote']; //当前所在地
                $data[$i]['regDate'] = $val['regDate']; //入藏时间
                $data[$i]['ecardFlag'] = isset($val['ecardFlag']) ? $val['ecardFlag'] : null; //ecardflag 为1 则为一卡通。其它情况为非一卡通。没返回就是 非一卡通
                $data[$i]['loanDate'] = isset($val['loanDate']) ? $val['loanDate'] : null; //借出时间 日期
                $data[$i]['loanTime'] = isset($val['loanTime']) ? $val['loanTime'] : null; //借出时间 时分秒
                $data[$i]['returnDate'] = isset($val['returnDate']) ? $val['returnDate'] : null; //应归还时间 日期
                $data[$i]['returnTime'] = isset($val['returnTime']) ? $val['returnTime'] : null; //应归还时间 时分秒
                $i++;
            }
            return ['code' => 200, 'msg' => '获取成功', 'content' => $data];
        }
        return ['code' => 202, 'msg' => '暂无数据'];
    }
    /**
     * 获取书籍状态文字
     * @param status
     */
    public function getBookStatusName($status)
    {
        if (empty($status)) return '其他';
        $status_name = [
            'a' => '分编',
            'b' => '入藏',
            'c' => '在装订',
            'd' => '已合并',
            'e' => '修补',
            'f' => '丢失',
            'g' => '剔除',
            'h' => '普通借出',
            'i' => '预约',
            'j' => '阅览借出',
            'k' => '资产状态',
            'l' => '预借',
            'm' => '互借',
            'n' => '闭架借阅',
            'o' => '赠送',
            'p' => '交换出',
            'q' => '调拨',
            't' => '转送',
            'x' => '临时借出',
            's' => '下架'
        ];

        return $status_name[$status];
    }


    /**
     * 校验读者借书权限接口
     * @param $account  读者证号
     * @param $barcode  馆藏条码号    新书  测试环境固定：01079300000147  渝中解放碑重庆书城
     * @param $barcode  馆藏条码号    新书  测试环境固定：01079300000153  渝中大坪重庆购书中心
     * @param $barcode  馆藏条码号    新书  正式环境固定：01039299999999  渝中解放碑重庆书城
     * @param $barcode  馆藏条码号    新书  正式环境固定：01039199999999  渝中大坪重庆购书中心
     * @return array
     * @param 01079300000147   01079300000153
     *
     *  private static $cqscAdminName = 'cqsc_bxdd_yz';//正式地址  操作管理员账号 渝中解放碑重庆书城
       private static $cqscPassword = '1234qwer';//正式地址  操作管理员密码

       private static $gszxAdminName = 'gszx_bxdd_yz';//正式地址  操作管理员账号 渝中大坪重庆购书中心
       private static $gszxPassword = '1234qwer';//正式地址  操作管理员密码
     */
    public function validateBorrow($account, $barcode = null, $shop_id = null)
    {
        $new_book_fixed_barcode = config('other.new_book_fixed_barcode');
        // if ($barcode == '01039299999999' || $barcode == '01039199999999') {
        if ($barcode == $new_book_fixed_barcode) {
            return ['code' => 202, 'msg' => '条形码：' . $barcode . '不允许借阅'];
        }

        list($adminName, $password) = $this->getManageAccount($shop_id);

        if (empty($barcode)) {
            //独立书店，馆藏点
            if ($shop_id == 1) {
                //YZT_CQSC  渝中解放碑重庆书城
                //$barcode = '01079300000147';//测试
                $barcode = $new_book_fixed_barcode; //正式
            } else {
                //YZT_GSZX 渝中大坪重庆购书中心
                // $barcode = '01079300000153';//测试
                $barcode = $new_book_fixed_barcode; //正式
            }
        }

        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token = $this->getAccessToken();
        }

        // dump($access_token);die;

        $url = self::$serviceAddr . self::$validateBorrow;
        $param = [
            'params' => [
                'cardno' => $account,
                'barcode' => $barcode,
            ],
            'admin' => [
                'adminName' => $adminName,
                'password' => md5($password),
                // 'password' => 'ee4dd839109f5112def48acbbaf00113',
                'loginWay' => 'DLibsApi',
                'ip' => '127.0.0.1',
            ]
        ];
        // dump($param);
        // dump($url . '?access_token=' . $access_token);
        $param = json_encode($param);

        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组

        //接口报错返回null
        if (empty($results)) {
            Log::channel('libapi')->info('URL：' . $url);
            Log::channel('libapi')->info(json_decode($param, true));
            //写入错误日志
            Log::channel('libapi')->info($results);
            return ['code' => 203, 'msg' => '服务器异常，请联系管理员处理'];
        }
        //dump($result);die;
        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token = $this->getAccessToken();
            // cache("lib_access_token", $access_token, 3600);//缓存3600秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }

        Log::channel('libapi')->info('URL：' . $url);
        Log::channel('libapi')->info(json_decode($param, true));
        //写入错误日志
        Log::channel('libapi')->info($results);

        if (isset($results['code']) && $results['code'] == 1) {
            return ['code' => 200, 'msg' => '可以借阅'];
        }

        return ['code' => 202, 'msg' => $results['message']];
    }

    /**
     * 流通-校验归还接口-需授权
     * @param $barcode  馆藏条码号
     * @return array
     */
    public function validateReturn($barcode)
    {
        //  $adminName = self::$adminName;
        //  $password = self::$password;
        $barcode = str_replace(config('other.lib_book_prefix'), '', $barcode);

        list($adminName, $password) = $this->getManageAccount();

        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token = $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$validateReturn;

        $param = [
            'params' => [
                'barcode' => $barcode,
            ],
            'admin' => [
                'adminName' => $adminName,
                'password' => md5($password),
                //'password' => 'ee4dd839109f5112def48acbbaf00113',
                'loginWay' => 'DLibsApi',
                'ip' => '127.0.0.1',
            ]
        ];

        $param = json_encode($param);

        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组

        //接口报错返回null
        if (empty($results)) {
            return ['code' => 203, 'msg' => '服务器异常，请联系管理员处理'];
        }
        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token = $this->getAccessToken();
            // cache("lib_access_token", $access_token, 3600);//缓存3600秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }

        Log::channel('libapi')->info('URL：' . $url);
        Log::channel('libapi')->info(json_decode($param, true));
        //写入错误日志
        Log::channel('libapi')->info($results);

        //dump($results);die;
        if (isset($results['code']) && $results['code'] == 1) {
            return ['code' => 200, 'msg' => '可以归还'];
        }

        return ['code' => 202, 'msg' => $results['message']];
    }


    /**
     *  2.13流通-借书接口-需授权
     * @param $cardno  读者证号
     * @param $barcode  馆藏条码号
     * @param $borrowDateTime  借书时间
     * @return array
     */
    public function bookBorrow($cardno, $barcode, $borrowDateTime = null, $shop_id = null)
    {
        empty($borrowDateTime) && $borrowDateTime = date('Y-m-d H:i:s');
        // $adminName = self::$adminName;
        // $password = self::$password;

        list($adminName, $password) = $this->getManageAccount($shop_id);

        //  $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token = $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$borrow;

        $param = [
            'params' => [
                'cardno' => $cardno,
                'barcode' => $barcode,
                'borrowDateTime' => $borrowDateTime,
            ],
            'admin' => [
                'adminName' => $adminName,
                'password' => md5($password),
                //'password' => 'ee4dd839109f5112def48acbbaf00113',
                'loginWay' => 'DLibsApi',
                'ip' => '127.0.0.1',
            ]
        ];


        $book_borrow_param = $param;
        $param = json_encode($param);

        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组
        // dump($param);
        // dump($results);
        // die;
        //接口报错返回null
        if (empty($results)) {
            //写入错误日志
            Log::write($book_borrow_param, 'book_borrow_log');
            //写入错误日志
            Log::write($results, 'book_borrow_log');

            return ['code' => 203, 'msg' => '服务器异常，请联系管理员处理'];
        }

        //dump($results);die;
        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token = $this->getAccessToken();
            // cache("lib_access_token", $access_token, 3600);//缓存3600秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }

        //写入错误日志
        Log::write($book_borrow_param, 'book_borrow_log');
        //写入错误日志
        Log::write($results, 'book_borrow_log');

        if (isset($results['code']) && $results['code'] == 1) {
            return ['code' => 200, 'msg' => '借阅成功', 'content' => $results['objectData']['asset']];
        }

        return ['code' => 202, 'msg' => $results['message']];
    }



    /**
     *  流通-归还接口-需授权
     * @param $barcode  馆藏条码号
     * @param $borrowDateTime  归还时间
     * @return array
     */
    public function bookReturn($barcode, $returnDate = null)
    {

        $barcode = str_replace(config('other.lib_book_prefix'), '', $barcode);

        empty($returnDate) && $returnDate = date('Y-m-d H:i:s');
        // $adminName = self::$adminName;
        // $password = self::$password;

        list($adminName, $password) = $this->getManageAccount();

        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token = $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$returnBook;

        $param = [
            'params' => [
                'barcode' => $barcode,
                'returnDate' => $returnDate,
            ],
            'admin' => [
                'adminName' => $adminName,
                'password' => md5($password),
                // 'password' => 'ee4dd839109f5112def48acbbaf00113',
                'loginWay' => 'DLibsApi',
                'ip' => '127.0.0.1',
            ]
        ];
        $book_return_param = $param;
        $param = json_encode($param);

        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组

        //接口报错返回null
        if (empty($results)) {
            //写入错误日志
            Log::write($book_return_param, 'book_return_log');
            //写入错误日志
            Log::write($results, 'book_return_log');

            return ['code' => 203, 'msg' => '服务器异常，请联系管理员处理'];
        }
        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token = $this->getAccessToken();
            // cache("lib_access_token", $access_token, 3600);//缓存3600秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }

        //写入错误日志
        Log::write($book_return_param, 'book_return_log');
        //写入错误日志
        Log::write($results, 'book_return_log');

        if (isset($results['code']) && $results['code'] == 1) {
            return ['code' => 200, 'msg' => '归还成功'];
        }

        return ['code' => 202, 'msg' => $results['message']];
    }

    /**
     *  流通-续借-续借单条-需授权
     * @param $barcode  馆藏条码号
     * @return array
     */
    public function renewBook($barcode)
    {
        empty($returnDate) && $returnDate = date('Y-m-d H:i:s');
        $adminName = self::$adminName;
        $password = self::$password;

        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token = $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$renew;

        $param = [
            'params' => [
                'barcode' => $barcode,
            ],
            'admin' => [
                'adminName' => $adminName,
                'password' => md5($password),
                // 'password' => 'ee4dd839109f5112def48acbbaf00113',
                'loginWay' => 'DLibsApi',
                'ip' => '127.0.0.1',
            ]
        ];

        $param = json_encode($param);

        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组

        //接口报错返回null
        if (empty($results)) {
            Log::channel('libapi')->info('URL：' . $url);
            Log::channel('libapi')->info(json_decode($param, true));
            //写入错误日志
            Log::channel('libapi')->info($results);

            return ['code' => 203, 'msg' => '服务器异常，请联系管理员处理'];
        }
        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token = $this->getAccessToken();
            // cache("lib_access_token", $access_token, 3600);//缓存3600秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }

        Log::channel('libapi')->info('URL：' . $url);
        Log::channel('libapi')->info(json_decode($param, true));
        //写入错误日志
        Log::channel('libapi')->info($results);

        if (isset($results['code']) && $results['code'] == 1) {
            return ['code' => 200, 'msg' => '续借成功', 'content' => $results['objectData']['asset']];
        }
        return ['code' => 202, 'msg' => $results['message']];
    }


    /**
     * 读者证-办证接口-需授权
     * @param $cardno  读者证号
     * @param $equipno  芯片号
     * @param $loginName  登录名
     * @param $idno       身份证
     * @param $realName  读者姓名
     * @param $password  登录密码
     * @param $cardType  读者证类型    45
     * @param $cerType  证件类别，身份证：idno    其他  字符串“6”
     * @param $eCardType
     * @param $etcCode  证件号码
     * @param $birth  出生年月日，格式：2019-01-01
     * @param $gender  性别，男：M 女：F
     * @param $workunit  工作单位
     * @param $address  联系地址
     * @param $zip  邮编
     * @param $phone  电话号码
     * @param $mobile  手机号码
     * @param $faxno  传真号码
     * @param $email  电子邮箱
     * @param $class1  分类1-所学专业
     * @param $class2  分类2-文化程度
     * @param $class3  分类3-行政职务
     * @param $class4  分类4-专业职称
     * @param $reviewLevel  书评级别
     * @param $acquisLevel  荐购级别
     * @param $notes  备注
     * @param $payWay  支付方式，现金：Cash  微信：WXin
     * @param $totalMoney  押金数额，单位：分
     *
     *
     *
     * 1：cerType 代码  6
     * 2：“前面 idno 身份证号码一致   为身份证号码 加 一个字母” 可以传
     * 3：idno 就不要传了
     * 4：其他的参数和之前参数一样     证件号码为  etcCode + 字母 Z
     * @return array
     * array(2) {
       ["params"] => array(29) {
           ["eCard"] => string(4) "true"
           ["cardno"] => string(14) "01131000000002"
           ["equipno"] => string(14) "01131000000002"
           ["loginName"] => string(14) "01131000000002"
           ["idno"] => string(14) "01131000000002"
           ["realName"] => string(12) "测试读者"
           ["password"] => string(7) "bxdd123"
           ["cardType"] => string(2) "45"
           ["eCardType"] => string(1) "1"
           ["cerType"] => string(4) "idno"
           ["etcCode"] => string(1) "1"
           ["birth"] => string(10) "2019-01-01"
           ["gender"] => string(1) "M"
           ["workunit"] => string(1) "1"
           ["address"] => string(1) "1"
           ["zip"] => string(1) "1"
           ["phone"] => string(11) "13258545262"
           ["mobile"] => string(11) "13258545262"
           ["faxno"] => string(1) "1"
           ["email"] => string(1) "1"
           ["class1"] => string(1) "1"
           ["class2"] => string(1) "3"
           ["class3"] => string(1) "3"
           ["class4"] => string(1) "3"
           ["reviewLevel"] => string(1) "1"
           ["acquisLevel"] => string(1) "1"
           ["notes"] => string(0) ""
           ["payWay"] => string(4) "Cash"
           ["totalMoney"] => string(5) "10000"
           }
           ["admin"] => array(4) {
           ["adminName"] => string(4) "bxdd"
           ["password"] => string(32) "ee4dd839109f5112def48acbbaf00113"
           ["loginWay"] => string(8) "DLibsApi"
           ["ip"] => string(9) "127.0.0.1"
           }
       }
     */
    public function readerIdAdd($data = null, $payWay = 'WXin')
    {
        $adminName = self::$adminName;
        $password = self::$password;

        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token = $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$readerIdAdd;
        //dump($url);die;
        $param = [
            'params' => [
                "eCard" => "true",
                'cardno' => $data['reader_id'],
                'equipno' => $data['reader_id'],
                'loginName' => $data['reader_id'],
                //'idno'=>$data['certificate_type'] == 1 ? $data['id_card'] : '',//其他不需要此参数
                'idno' => $data['id_card'],
                'realName' => $data['username'],
                'password' => substr($data['id_card'], 6, 8),
                'cardType' => $data['card_type'],
                'eCardType' => '', //传空字符串，接口自己处理
                'cerType' => $data['certificate_type'] == 1 ? 'idno' : '6',
                'etcCode' => $data['certificate_type'] == 1 ? $data['id_card'] : $data['id_card'] . 'Z',
                'birth' => $data['birthday'],
                'gender' => $data['sex'] == 1 ? 'M' : 'F',
                'workunit' => '',
                'address' => $data['province'] . $data['city'] . $data['district'] . $data['street'] . $data['address'],
                'zip' => $data['zip'],
                'phone' => $data['phone'],
                'mobile' => $data['tel'],
                'faxno' => 1,
                'email' => $data['email'],
                'class1' => 1,
                'class2' => $data['culture'], //文化程度
                'class3' => $data['position'], //职业
                'class4' => 1,
                'reviewLevel' => 1,
                'acquisLevel' => 1,
                'notes' => $data['remark'],
                // 'payWay'=>'Cash',
                'payWay' => $payWay,
                'totalMoney' => empty($data['cash']) ? 0 : $data['cash'] * 100, //换算成分
            ],
            'admin' => [
                'adminName' => $adminName,
                'password' => md5($password),
                // 'password' => 'ee4dd839109f5112def48acbbaf00113',
                'loginWay' => 'DLibsApi',
                'ip' => '127.0.0.1',
            ]
        ];

        $online_registration_param = $param;
        $param = json_encode($param);

        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组
        //接口报错返回null
        if (empty($results)) {
            //写入错误日志
            Log::write($online_registration_param, 'online_registration_log');
            //写入错误日志
            Log::write($results, 'online_registration_log');

            return ['code' => 203, 'msg' => '服务器异常，请联系管理员处理'];
        }


        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token = $this->getAccessToken();
            // cache("lib_access_token", $access_token, 3600);//缓存3600秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }

        //写入错误日志
        Log::write($online_registration_param, 'online_registration_log');
        //写入错误日志
        Log::write($results, 'online_registration_log');

        if (isset($results['code']) && $results['code'] == 1) {
            return ['code' => 200, 'msg' => '办证成功'];
        }
        return ['code' => 202, 'msg' => $results['message']];
    }

    /**
     *  读者证-在线办证-获取在线办证参数集合
     */
    public function getOnlineReaderCardCreateParam()
    {
        /*  $adminName = self::$adminName;
       $password = self::$password;*/

        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token = $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$getOnlineReaderCardCreateParam;
        $param = '{}';

        //dump($url . '?access_token=' . $access_token);
        //dump('http://222.178.152.2:18083/indiglibApi/api/v1/param/onlineReaderCardCreateParam/getOnlineReaderCardCreateParam?access_token=d3ae63924adf2b5bcb0fa40c5d4ea075');
        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token = $this->getAccessToken();
            // cache("lib_access_token", $access_token, 3600);//缓存3600秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }

        if (isset($results['code']) && $results['code'] == 1) {
            return ['code' => 200, 'msg' => '获取成功', 'content' => $results['objectData']];
        }
        return ['code' => 202, 'msg' => $results['message']];
    }

    /**
     *  读者-查询读者列表(非注销)-根据身份证号码-需授权  (已对接)
     * @param $idno  身份证号码
     * @return array
     *
     *  //查询的是  ，是否在本馆办过读者证，在其他馆办理过的，查询不到
     */
    public function getReaderPageInfoByIdno($idno, $page = 1, $limit = 10)
    {
        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token = $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$getReaderPageInfoByIdno;

        $param = [
            'idno' => $idno,
            'pageNum' => $page,
            'pageSize' => $limit,
        ];

        $param = json_encode($param);

        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token = $this->getAccessToken();
            // cache("lib_access_token", $access_token, 3600);//缓存3600秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }
        Log::channel('libapi')->info('URL：' . $url);
        Log::channel('libapi')->info(json_decode($param, true));
        //写入错误日志
        Log::channel('libapi')->info($results);

        if ($results['code'] === 1 && !empty($results['objectData']['list'])) {
            return ['code' => 200, 'msg' => '获取成功', 'content' => $results['objectData']['list']];
        }
        return ['code' => 202, 'msg' => $results['message']];
    }

    /**
     *  读者证-挂失-需授权
     * @param $account  读者证号
     * @return array
     */
    public function lost($account)
    {
        $adminName = self::$adminName;
        $password = self::$password;

        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token = $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$lost;
        $param = [
            'params' => [
                'cardno' => $account,
            ],
            'admin' => [
                'adminName' => $adminName,
                'password' => md5($password),
                // 'password' => 'ee4dd839109f5112def48acbbaf00113',
                'loginWay' => 'DLibsApi',
                'ip' => '127.0.0.1',
            ]
        ];
        $param = json_encode($param);

        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token = $this->getAccessToken();
            // cache("lib_access_token", $access_token, 3600);//缓存3600秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }

        Log::channel('libapi')->info('URL：' . $url);
        Log::channel('libapi')->info(json_decode($param, true));
        //写入错误日志
        Log::channel('libapi')->info($results);

        if (isset($results['code']) && $results['code'] == 1) {
            return ['code' => 200, 'msg' => '挂失成功'];
        }
        return ['code' => 202, 'msg' => $results['message']];
    }

    /**
     *  读者证-挂失恢复-需授权
     * @param $account  读者证号
     * @return array
     */
    public function lostRecover($account)
    {
        $adminName = self::$adminName;
        $password = self::$password;

        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token = $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$lostRecover;
        $param = [
            'params' => [
                'cardno' => $account,
            ],
            'admin' => [
                'adminName' => $adminName,
                'password' => md5($password),
                //'password' => 'ee4dd839109f5112def48acbbaf00113',
                'loginWay' => 'DLibsApi',
                'ip' => '127.0.0.1',
            ]
        ];
        $param = json_encode($param);

        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token = $this->getAccessToken();
            // cache("lib_access_token", $access_token, 3600);//缓存3600秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }

        Log::channel('libapi')->info('URL：' . $url);
        Log::channel('libapi')->info(json_decode($param, true));
        //写入错误日志
        Log::channel('libapi')->info($results);

        if (isset($results['code']) && $results['code'] == 1) {
            return ['code' => 200, 'msg' => '取消挂失成功'];
        }
        return ['code' => 202, 'msg' => $results['message']];
    }


    /**
     * 读者证-更新读者密码-需授权
     * @param $account  读者证号
     * @param $origPassword  读者旧密码
     * @param $newPassword  读者新密码
     * @return array
     */
    public function updateReaderPassword($account, $origPassword, $newPassword)
    {
        $adminName = self::$adminName;
        $password = self::$password;

        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token = $this->getAccessToken();
        }
        //dump($access_token);die;
        $url = self::$serviceAddr . self::$updateReaderPassword;
        $param = [
            'params' => [
                'cardno' => $account,
                'origPassword' => md5($origPassword),
                'newPassword' => md5($newPassword),
                'isMd5Password' => true
            ],
            'admin' => [
                'adminName' => $adminName,
                'password' => md5($password),
                // 'password' => 'ee4dd839109f5112def48acbbaf00113',
                'loginWay' => 'DLibsApi',
                'ip' => '127.0.0.1',
            ]
        ];
        $param = json_encode($param);

        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token = $this->getAccessToken();
            // cache("lib_access_token", $access_token, 3600);//缓存3600秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }

        Log::channel('libapi')->info('URL：' . $url);
        Log::channel('libapi')->info(json_decode($param, true));
        //写入错误日志
        Log::channel('libapi')->info($results);

        if (isset($results['code']) && $results['code'] == 1) {
            return ['code' => 200, 'msg' => '修改成功'];
        }
        return ['code' => 202, 'msg' => $results['message']];
    }
    /**
     * 读者财经-欠款-查询读者欠款分页列表-根据读者证号-需授权
     * @param account 读者证号
     */
    public function getReaderArrearsListPageInfo($account, $page = 1, $limit = 10)
    {
        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token = $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$getReaderArrearsListPageInfo;
        $param = [
            'cardno' => $account,
            'pageNum' => $page,
            'pageSize' => $limit,
        ];

        $param = json_encode($param);

        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token = $this->getAccessToken();
            // cache("lib_access_token", $access_token, 3600);//缓存3600秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }

        Log::channel('libapi')->info('URL：' . $url);
        Log::channel('libapi')->info(json_decode($param, true));
        //写入错误日志
        Log::channel('libapi')->info($results);

        if (isset($results['code']) && $results['code'] == 1) {
            return ['code' => 200, 'msg' => '获取成功', 'content' => $results['objectData']];
        }
        return ['code' => 202, 'msg' => $results['message']];
    }

    /**
     * 读者财经-欠款-支付欠款-需授权
     * @param readerId 读者ID(为空或空字符串则查全部分馆) 为图书馆的id
     * @param arrearsIdList 欠费列表id
     * @param payWay 支付方式，现金：Cash，微信：WXin ，支付宝：APay
     *
     * array(3) {
           ["code"] => int(1)
           ["message"] => string(15) "交欠款成功"
           ["objectData"] => string(0) ""
           }
     */
    public function payArrears($account = null, $arrearsIdList = [], $payWay = '1')
    {
        //   $payWay = $payWay == 1 ? 'WXin' : 'Score';//1微信  2 积分
        $payWay = $payWay == 1 ? 'WXin' : 'ScoreDeduction'; //1微信  2 积分

        $account_info = $this->getReaderInfo($account);
        if ($account_info['code'] == 200) {
            $reader_id = $account_info['content']['reader']['id'];
        } else {
            return ['code' => 202, 'msg' => '获取用户信息失败'];
        }

        $adminName = self::$adminName;
        $password = self::$password;

        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token = $this->getAccessToken();
        }

        //转换为int类型
        $arrearsIdListArr = [];
        foreach ($arrearsIdList as $key => $val) {
            $arrearsIdListArr[] = (int)$val;
        }

        $url = self::$serviceAddr . self::$payArrears;
        $param = [
            'params' => [
                'readerId' => $reader_id,
                'arrearsIdList' => $arrearsIdListArr, //[1837,1836,1835]
                'payWay' => $payWay,
                'flowNumber' => '',
            ],
            'admin' => [
                'adminName' => $adminName,
                'password' => md5($password),
                // 'password' => 'ee4dd839109f5112def48acbbaf00113',
                'loginWay' => 'DLibsApi',
                'ip' => '127.0.0.1',
            ]
        ];
        $param = json_encode($param);

        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token = $this->getAccessToken();
            // cache("lib_access_token", $access_token, 3600);//缓存3600秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }
        //写入错误日志
        Log::write(json_decode($param, true), 'owe_pay_log');
        //写入错误日志
        Log::write($results, 'owe_pay_log');


        if (isset($results['code']) && $results['code'] == 1) {
            return ['code' => 200, 'msg' => '缴费成功'];
        }
        return ['code' => 202, 'msg' => $results['message']];
    }


    /**
     * 2.23微信-获取微信accessToken
     * @param access_token 文华accesstoken
     */
    public function getWxAccessToken()
    {
        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token = $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$wxAccessToken;

        $param = '{}';

        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token = $this->getAccessToken();
            // cache("lib_access_token", $access_token, 3600);//缓存3600秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }
        //写入错误日志
        Log::write($param, 'other_log');
        //写入错误日志
        Log::channel('libapi')->info($results);

        if (isset($results['code']) && $results['code'] == 1) {
            $data = json_decode($results['objectData']['accessToken'], true);
            $results['objectData']['accessToken'] = $data['access_token'];
            $results['objectData']['expires_in'] = $data['expires_in'];

            return ['code' => 200, 'msg' => '获取成功', 'content' => $results['objectData']];
        }
        return ['code' => 202, 'msg' => $results['message']];
    }

    /**
     * 云cloud-读者-校验读者身份证号是否存在(校验是否存在非注销状态读者)-需授权
     * 这个接口不能判断身份证是否在本馆办过证，还需要另外一个接口，配合查询是否在本馆办过证的接口（如果返回是，则在本馆办过证，如果返回否，表示在其他馆办过证）
     * @param idno 身份证号码
     */
    public function validateIdnoIsExist($idno)
    {
        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token = $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$validateIdnoIsExist;
        $param = [
            'idno' => $idno,
        ];
        $param = json_encode($param);

        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token = $this->getAccessToken();
            // cache("lib_access_token", $access_token, 3600);//缓存3600秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }

        //写入错误日志
        Log::channel('libapi')->info('URL：' . $url);
        Log::channel('libapi')->info(json_decode($param, true));
        //写入错误日志
        Log::channel('libapi')->info($results);

        if (empty($results)) {
            return ['code' => 203, 'msg' => '网络错误'];
        }

        //原接口判断
        if (isset($results['code']) && $results['code'] == 1) {
            //$results['objectData']['isExist'] true 表示已存在  false  不存在
            //if(isset($results['code']) && $results['code'] == 1 && isset($results['objectData']['isExist']) && $results['objectData']['isExist']){ //新接口判断
            return ['code' => 200, 'msg' => $results['message'], 'content' => $results['objectData']]; //表示办过证
        }
        return ['code' => 202, 'msg' => $results['message']]; //表示未办过证
    }

    /**
     * 读者证-证延期-网上服务读者自助延期-需授权
     * @param $account 读者证号
     */
    public function extendByReaderSelf($account)
    {
        $adminName = self::$adminName;
        $password = self::$password;

        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token = $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$extendByReaderSelf;
        $param = [
            'params' => [
                'cardno' => $account,
            ],
            'admin' => [
                'adminName' => $adminName,
                'password' => md5($password),
                // 'password' => 'ee4dd839109f5112def48acbbaf00113',
                'loginWay' => 'DLibsApi',
                'ip' => '127.0.0.1',
            ]
        ];

        $param = json_encode($param);

        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token = $this->getAccessToken();
            // cache("lib_access_token", $access_token, 3600);//缓存3600秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }

        //写入错误日志
        Log::channel('libapi')->info('URL：' . $url);
        Log::channel('libapi')->info(json_decode($param, true));
        //写入错误日志
        Log::channel('libapi')->info($results);

        if (isset($results['code']) && $results['code'] == 1) {
            return ['code' => 200, 'msg' => '操作成功', 'content' => $results['objectData']];
        }
        return ['code' => 202, 'msg' => $results['message']];
    }


    /**
     * front-微信-读者绑定-需授权（我们平台绑定后，推送绑定在文华系统）
     * @param $readerId 读者ID
     * @param $openid   微信open_id
     */
    public function wxBind($readerId, $open_id)
    {
        // $adminName = self::$adminName;
        // $password = self::$password;

        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token = $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$wxBind;
        $param = [
            'readerId' => $readerId,
            'openid' => $open_id,
            // 'params' => [
            //     'readerId' => $readerId,
            //     'openid' => $open_id,
            // ],
            // 'admin' => [
            //     'adminName' => $adminName,
            //     'password' => md5($password),
            //    // 'password' => 'ee4dd839109f5112def48acbbaf00113',
            //     'loginWay' => 'DLibsApi',
            //     'ip' => '127.0.0.1',
            // ]
        ];

        $param = json_encode($param);

        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组
        //    dump($results);die;
        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token = $this->getAccessToken();
            // cache("lib_access_token", $access_token, 3600);//缓存3600秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }

        //写入错误日志
        Log::channel('libapi')->info('URL：' . $url);
        Log::channel('libapi')->info(json_decode($param, true));
        //写入错误日志
        Log::channel('libapi')->info($results);

        if (isset($results['code']) && $results['code'] == 1) {
            return ['code' => 200, 'msg' => '操作成功', 'content' => $results['objectData']];
        }
        return ['code' => 202, 'msg' => $results['message']];
    }

    /**
     * 2.7front-微信-解除读者绑定-需授权（我们平台解绑后，推送解绑在文华系统）
     * @param $readerId 读者ID
     * @param $openid   微信open_id
     */
    public function wxUnBind($readerId, $open_id)
    {
        // $adminName = self::$adminName;
        // $password = self::$password;

        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token = $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$wxUnBind;
        $param = [
            'readerId' => $readerId,
            'openid' => $open_id,
            // 'params' => [
            //     'readerId' => $readerId,
            //     'openid' => $open_id,
            // ],
            // 'admin' => [
            //     'adminName' => $adminName,
            //     'password' => md5($password),
            //    // 'password' => 'ee4dd839109f5112def48acbbaf00113',
            //     'loginWay' => 'DLibsApi',
            //     'ip' => '127.0.0.1',
            // ]
        ];

        $param = json_encode($param);

        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token = $this->getAccessToken();
            // cache("lib_access_token", $access_token, 3600);//缓存3600秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }
        // dump($results);die;
        //写入错误日志
        Log::channel('libapi')->info('URL：' . $url);
        Log::channel('libapi')->info(json_decode($param, true));
        //写入错误日志
        Log::channel('libapi')->info($results);

        if (isset($results['code']) && $results['code'] == 1) {
            return ['code' => 200, 'msg' => '操作成功', 'content' => $results['objectData']];
        }
        return ['code' => 202, 'msg' => $results['message']];
    }

    /**
     * 2.23读者-查询读者(基本信息)-根据微信openid-需授权
     * @param $openid   微信open_id
     */
    public function getReaderByOpenid($open_id)
    {
        // $adminName = self::$adminName;
        // $password = self::$password;

        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token = $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$getReaderByOpenid;
        $param = [
            'openid' => $open_id,
            // 'params' => [
            //     'openid' => $open_id,
            // ],
            // 'admin' => [
            //     'adminName' => $adminName,
            //     'password' => md5($password),
            //    // 'password' => 'ee4dd839109f5112def48acbbaf00113',
            //     'loginWay' => 'DLibsApi',
            //     'ip' => '127.0.0.1',
            // ]
        ];

        $param = json_encode($param);

        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token = $this->getAccessToken();
            // cache("lib_access_token", $access_token, 3600);//缓存3600秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }

        //写入错误日志
        Log::channel('libapi')->info('URL：' . $url);
        Log::channel('libapi')->info(json_decode($param, true));
        //写入错误日志
        Log::channel('libapi')->info($results);

        if (isset($results['code']) && $results['code'] == 1) {
            return ['code' => 200, 'msg' => '操作成功', 'content' => $results['objectData']];
        }
        return ['code' => 202, 'msg' => $results['message']];
    }


    /**
     * //读者-查询读者(基本信息)-根据读者id-需授权
     * @param $reader_id   文华系统读者id   在 条形码获取信息接口会返回一个  readerId  表示当前借阅用户的id
     */
    public function getReaderById($reader_id)
    {
        // $adminName = self::$adminName;
        // $password = self::$password;

        $access_token = Cache::get('lib_access_token');
        if (empty($access_token)) {
            $access_token = $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$getReaderById;
        $param = [
            'id' => $reader_id,
        ];

        $param = json_encode($param);

        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token = $this->getAccessToken();
            // cache("lib_access_token", $access_token, 3600);//缓存3600秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }

        //写入错误日志
        Log::channel('libapi')->info('URL：' . $url);
        Log::channel('libapi')->info(json_decode($param, true));
        //写入错误日志
        Log::channel('libapi')->info($results);

        if (isset($results['code']) && $results['code'] == 1) {
            return ['code' => 200, 'msg' => '操作成功', 'content' => $results['objectData']];
        }
        return ['code' => 202, 'msg' => $results['message']];
    }

    /**
     * 获取借阅，归还，管理员账号
     * @param 书店 id
     */
    public function getManageAccount($shop_id = null)
    {
        // if (!empty($shop_id) || (isset(request()->admin_auth_info->way) && request()->admin_auth_info->way == 3)) {

        //     if(empty($shop_id)) $shop_id = request()->admin_auth_info->shop_id;

        //     //独立书店，馆藏点
        //     if ($shop_id == 1) {
        //         //YZT_CQSC  渝中解放碑重庆书城
        //         $adminName = self::$cqscAdminName;
        //         $password = self::$cqscPassword;
        //     } else {
        //         //YZT_GSZX 渝中大坪重庆购书中心
        //         $adminName = self::$gszxAdminName;
        //         $password = self::$gszxPassword;
        //     }
        // } else {
        $adminName = self::$adminName;
        $password = self::$password;
        //}
        return [$adminName, $password];
    }


    /**
     * 2.12front-读者借阅排行榜-结果列表
     * @param $sublib  分馆代码(为空或空字符串则查全部分馆)
     * @param $docType   文献类型(为空或空字符串则查全部文献类型)
     * @param $timeLimit   时间范围(距离今天多少天，时间范围只能为最近一周(7天)，最近一个月(30天)，最近三个月(90天)和最近六个月(180天)（timeLimit不为空时，起始时间和结束时间可为空，同时不为空时起始时间和结束时间的优先级更高）
     * @param $startDate   开始日期
     * @param $endDate   结束日期
     */
    public function frontReader($sublib, $docType, $timeLimit, $startDate = null, $endDate = null)
    {
        // $adminName = self::$adminName;
        // $password = self::$password;

        $access_token = cache('yzqlib_access_token');
        if (empty($access_token)) {
            $access_token = $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$frontReader;

        $param = [
            'sublib' => $sublib,
            'docType' => $docType,
            'timeLimit' => $timeLimit,
            'startDate' => $startDate,
            'endDate' => $endDate,
        ];

        $param = json_encode($param);

        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token = $this->getAccessToken();
            // cache("yzqlib_access_token", $access_token, 3600);//缓存3600秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }

        //写入错误日志
        Log::channel('libapi')->info('URL：' . $url);
        Log::channel('libapi')->info(json_decode($param, true));
        //写入错误日志
        Log::channel('libapi')->info($results);

        if (isset($results['code']) && $results['code'] == 1) {
            return ['code' => 200, 'msg' => '操作成功', 'content' => $results['objectData']];
        }
        return ['code' => 202, 'msg' => $results['message']];
    }

    /**
     * 2.13前台front-读者年龄借阅排行榜-结果列表
     * @param $sublib  分馆代码(为空或空字符串则查全部分馆)
     * @param $docType   文献类型(为空或空字符串则查全部文献类型)
     * @param $startDate   开始日期
     * @param $endDate   结束日期
     */
    public function frontReaderAge($sublib, $docType, $startDate, $endDate)
    {
        // $adminName = self::$adminName;
        // $password = self::$password;

        $access_token = cache('yzqlib_access_token');
        if (empty($access_token)) {
            $access_token = $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$frontReaderAge;

        $param = [
            'sublib' => $sublib,
            'docType' => $docType,
            'startDate' => $startDate,
            'endDate' => $endDate,
        ];

        $param = json_encode($param);

        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组
        dump($results);
        die;
        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token = $this->getAccessToken();
            // cache("yzqlib_access_token", $access_token, 3600);//缓存3600秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }

        //写入错误日志
        Log::channel('libapi')->info('URL：' . $url);
        Log::channel('libapi')->info(json_decode($param, true));
        //写入错误日志
        Log::channel('libapi')->info($results);

        if (isset($results['code']) && $results['code'] == 1) {
            return ['code' => 200, 'msg' => '操作成功', 'content' => $results['objectData']];
        }
        return ['code' => 202, 'msg' => $results['message']];
    }


    /**
     * @param $url
     * @param null $params
     * @param bool $json  json  格式数据    Content-Type  需要修改  成 application/json
     * @return mixed
     */
    private  static  function RequestCurl($url, $params = null, $json = false)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_TIMEOUT, 10);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        if (!empty($params)) {
            if (is_array($params)) {
                //如果传的是数组，就要进行对参数进行 &拼接
                $params = http_build_query($params);
            }
            if ($json) {
                curl_setopt(
                    $ch,
                    CURLOPT_HTTPHEADER,
                    array(
                        'Content-Type: application/json',
                        'Content-Length: ' . strlen($params)
                    )
                );
            }
            // curl_setopt($ch, CURLOPT_POST, 1);
            // curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        }
        //都是用post格式
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

        $body = curl_exec($ch);
        // dump(curl_error($ch));
        curl_close($ch);
        return $body;
    }
}
